<template>
  <div class="scores-overview">
    <el-row :gutter="20">

      <!-- 成绩统计卡片 -->
      <el-col :span="24">
        <el-card class="filter-card">
          <el-form :inline="true" :model="filterForm" class="filter-form">
            <el-form-item label="班级" >
              <el-select v-model="filterForm.class" placeholder="选择班级" clearable>
                <el-option
                    v-for="item in tea_classes"
                    :key="item.classId"
                    :label="item.name"
                    :value="item.classId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="课程">
              <el-select v-model="filterForm.course" placeholder="选择课程" clearable>
                <el-option
                    v-for="item in tea_courses"
                    :key="item.courseId"
                    :label="item.name"
                    :value="item.courseId"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card class="stats-card">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ overviewData.average.toFixed(2) }}</div>
                <div class="stat-label">平均分</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ overviewData.passRate * 100 }}%</div>
                <div class="stat-label">及格率</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ overviewData.maxScore }}</div>
                <div class="stat-label">最高分</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ overviewData.sumStudent }}</div>
                <div class="stat-label">总人数</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

    </el-row>

    <el-row :gutter="20" class="mt-20">

      <!-- 成绩趋势图 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h3>班级课程分数段人数图</h3>
            </div>
          </template>
          <div class="chart-container">
            <div ref="gradeBands" style="width: 100%; height: 400px;"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h3>班级课程分数段人数比例图</h3>
            </div>
          </template>
          <div class="chart-container">
            <div ref="pieChartRef" class="pie-chart" style="width: 100%; height: 400px;"></div>
          </div>
        </el-card>
      </el-col>
      <!-- 成绩分布图 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h3>课程成绩分布</h3>
            </div>
          </template>
          <div ref="chartRef" class="chart-container" />
        </el-card>
      </el-col>
    </el-row>


  </div>
</template>

<script setup>
import {ref, onMounted, reactive, watch} from 'vue'
import * as echarts from 'echarts'
import {storeToRefs} from "pinia";
import { useTeacherStores } from "@/stores/teacherStores.js";
import { ElMessage } from "element-plus";
import axios from "axios";
import baseURL from "@/config/config.js";
// 统计数据
const overviewData = ref({
  average: 0,
  maxScore: 0,
  passRate: 0,
  sumStudent: 0
})
// 成绩分布统计
const classOverviewData = ref([
  { className: '', maxScore: 0, average: 0, passRate: 0 },
])
// 分数段
const scoreBandsData = ref([{label: 'A', sum: 0},{label: 'A', sum: 0},{label: 'A', sum: 0},{label: 'A', sum: 0},{label: 'A', sum: 0}])
const { tea_classes, tea_courses } = storeToRefs(useTeacherStores())
// 过滤表单
const filterForm = reactive({
  class: '',
  course: '',
  stuId: ''
})
// 处理搜索
const handleSearch = () => {
  if (filterForm.class === '' || filterForm.course === '' || !filterForm.class || !filterForm.course) {
    ElMessage({
      type: 'error',
      message: '请同时选择班级和课程才可查询'
    })
    return
  }

  axios({
    url: baseURL + '/score/get-overview',
    headers: {
      "Authorization": `Bearer ${localStorage.getItem('token')}`,
      "Content-Type": "application/json"
    },
    params: {
      classId: filterForm.class,
      courseId: filterForm.course,
    }
  }).then(({data}) => {
    console.log(data)
    overviewData.value = data.data
  })

  axios({
    url: baseURL + '/score/get-score-segments',
    headers: {
      "Authorization": `Bearer ${localStorage.getItem('token')}`,
      "Content-Type": "application/json"
    },
    params: {
      classId: filterForm.class,
      courseId: filterForm.course,
    }
  }).then(({data}) => {
    console.log(data)
    scoreBandsData.value = data.data
    updateScoreTrendChart()
  })
}
// 重置表单
const resetForm = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = ''
  })
}

watch(() => filterForm.course, v => {
  // 获取课程所有班级平均分
  if (v) {
    axios({
      url: baseURL + '/score/get-class-overview',
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`,
      },
      params: {
        courseId: filterForm.course,
      }
    }).then(({data}) => {
      console.log(data.data)
      classOverviewData.value = data.data
      if (chartInstance) {
        updateScoreDistributionChart(); // 调用更新图表的方法
      }
    }).catch(err => {
      console.log(err)
    })
  }
})

const gradeBands = ref(null) // 分数段图标
let gradeBandsChart = null
const chartRef = ref(null) // 成绩分布图表
let chartInstance = null
// 新增扇形图相关变量
const pieChartRef = ref(null)
let pieChartInstance = null

// 新增更新图表的方法
const initScoreTrendChart = () => {
  // 初始化echarts实例
  gradeBandsChart = echarts.init(gradeBands.value)
  // 新增扇形图初始化
  pieChartInstance = echarts.init(pieChartRef.value)
  // 分数段配置
  const bandsTip = [
    { label: '0-59'},
    { label: '60-69',},
    { label: '70-79',},
    { label: '80-89'},
    { label: '90-100'}
  ]
  // 设置图表配置项
  const option = {
    title: {
      text: '分数段人数分布',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        const param = params[0]
        return `${param.name}<br/>人数: ${param.value}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: bandsTip.map(band => band.label),
      axisTick: {
        alignWithLabel: true
      },
      axisLabel: {
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '人数',
      min: 0,
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: [{
      name: '人数',
      type: 'bar',
      barWidth: '60%',
      // 直接使用数据中的sum字段作为人数
      data: scoreBandsData.value.map(v => v.sum),
      itemStyle: {
        color: '#409EFF',
        borderRadius: [4, 4, 0, 0]
      },
      label: {
        show: true,
        position: 'top'
      }
    }]
  }
  // 应用配置并渲染图表
  gradeBandsChart.setOption(option)
// 扇形图配置
  const pieOption = {
    tooltip: {
      trigger: 'item',
      formatter: function (params) {
        return `${bandsTip[params.dataIndex].label}<br/>比例：${params.percent}%`
      }
    },
    series: [
      {
        name: '分数段比例',
        type: 'pie',
        radius: '70%',
        center: ['50%', '50%'],
        data: [],
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        }
      }
    ]
  }
  pieChartInstance.setOption(pieOption)
}
const updateScoreTrendChart = () => {
  if (!chartInstance) return; // 确保图表已初始化

  gradeBandsChart.setOption({
    series: [{
      name: '人数',
      type: 'bar',
      barWidth: '60%',
      // 直接使用数据中的sum字段作为人数
      data: scoreBandsData.value.map(v => v.sum),
      itemStyle: {
        color: '#409EFF',
        borderRadius: [4, 4, 0, 0]
      },
      label: {
        show: true,
        position: 'top'
      }
    }]
  });

  // 计算扇形图数据
  const total = scoreBandsData.value.reduce((acc, cur) => acc + cur.sum, 0);
  const pieData = scoreBandsData.value.map(item => ({
    name: item.label,
    value: item.sum,
    percent: ((item.sum / total) * 100).toFixed(1)
  }));

  // 更新扇形图数据
  pieChartInstance.setOption({
    series: [{
      data: pieData,
      label: {
        formatter: `{b}\n{d}%` // 使用计算好的百分比
      },// 确保 tooltip 也使用正确的格式
      tooltip: {
        formatter: `{b}<br/>比例：{d}%`
      }
    }]
  });
};
const initScoreDistributionChart = () => {
  chartInstance = echarts.init(chartRef.value)

  chartInstance.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: ['最高分', '平均分', '及格率']
    },
    xAxis: {
      type: 'category',
      data: classOverviewData.value.map((item) => item.className)
    },
    yAxis: [
      {
        type: 'value',
        name: '分数',
        min: 0,
        max: 100,
        interval: 20,
        axisLabel: {
          formatter: '{value} 分'
        }
      },
      {
        type: 'value',
        name: '及格率',
        min: 0,
        max: 1,
        interval: 0.2,
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '最高分',
        type: 'line',
        data: classOverviewData.value.map((item) => item.maxScore)
      },
      {
        name: '平均分',
        type: 'line',
        data: classOverviewData.value.map((item) => item.average)
      },
      {
        name: '及格率',
        type: 'line',
        yAxisIndex: 1,
        data: classOverviewData.value.map((item) => item.passRate)
      }
    ]
  })
}
const updateScoreDistributionChart = () => {
  if (!chartInstance) return; // 确保图表已初始化

  chartInstance.setOption({
    xAxis: {
      type: 'category',
      data: classOverviewData.value.map((item) => item.className)
    },
    series: [
      {
        name: '最高分',
        data: classOverviewData.value.map(item => item.maxScore)
      },
      {
        name: '平均分',
        data: classOverviewData.value.map(item => item.average)
      },
      {
        name: '及格率',
        data: classOverviewData.value.map(item => item.passRate)
      }
    ]
  });
};
onMounted(() => {
  initScoreDistributionChart()
  initScoreTrendChart()

  // 监听窗口大小变化，重绘图表
  window.addEventListener('resize', () => {
    chartInstance?.resize()
    gradeBandsChart?.resize()
  })
})
</script>

<style scoped>
.scores-overview {
  padding: 20px;
}
.filter-card {
  margin-bottom: 5px;
  width: 100%;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
/* 让表单元素平均分布 */
.filter-form .el-form-item {
  flex: 1;
  min-width: 200px; /* 防止元素过窄 */
  margin-right: 10px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stats-card {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background-color: #f8fafc;
  border-radius: 8px;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  line-height: 1.2;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
  margin-top: 8px;
}

.stat-trend {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  margin-top: 8px;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.stat-trend.up {
  color: #67c23a;
  background-color: rgba(103, 194, 58, 0.1);
}

.stat-trend.down {
  color: #f56c6c;
  background-color: rgba(245, 108, 108, 0.1);
}

.mt-20 {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  color: #1f2937;
}

.header-actions {
  display: flex;
  align-items: center;
}

.chart-container {
  padding: 10px;
}

.trend-up {
  color: #67c23a;
}

.trend-down {
  color: #f56c6c;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.chart-container {
  width: 100%;
  height: 400px;
}
</style> 